<?php

/**
 * Connects to database and returns one object (at most) for the specified SQL query string
 *
 * @param unknown $sqlQuery - SQL query string
 * @return stdClass with fields for each column
 */

function doGetSingleResult($sqlQuery) {
	connectToDatabase();
	$sql = createQuery($sqlQuery);
	return mysql_fetch_object($sql);
}

/**
 * Connects to database and return a list of objects for the specified SQL query string
 *
 * @param unknown $sqlQuery - SQL query string
 * @return stdClass[] with fields for each column
 */


function doGetListResult($sqlQuery) {
	$sql = createQuery($sqlQuery);
	return queryToArray($sql);
}

/**
 * Creates query and prints error message if it failed.
 * @param $sqlQuery
 * @return unknown_type
 */

function createQuery($sqlQuery) {
	$sql = mysql_query($sqlQuery);
	if (!$sql) {
		echo "SQL: ".$sqlQuery."<br/>";
		die('Invalid query: ' . mysql_error());
	}
	return $sql;
}

/**
 * Converts a sql query to an array for easier usage.
 */

function queryToArray($sql) {
	$array = array();
	while($row = mysql_fetch_object($sql)) {
		$array[] = $row;
	}
	return $array;
}

/**
 * Prints a JSON message and exists
 *
 * @param unknown $object
 */

function jsonOut($object) {
	header("Content-Type: application/json");
	echo json_encode($object);
	exit;
}

/**
 * Prints an error message and exists the Slim application
 *
 * @param unknown $code - a code of some kind (usually an integer or a not localized string)
 * @param unknown $message - a localized message or error description
 */


function errorOut($code, $message) {
	\Slim\Slim::getInstance()->halt(500, "{ 'code' : '$code', 'message' : '$message' }");
}

?>